//获取应用实例
const app = getApp();
// 引入AES.js
var baseJs = require("../../common/base.js");
var json1 = [];
var json2 = [];
var giftMaName = '';
var giftMaName1 = '';
var giftMaName2 = '';
var giftMaName3 = '';
var giftMaId = '';
var giftGiveMaEdu = '';
var giftGiveMaEduValidityDay = '';
var giftConsumeMaEdu = '';
var giftSaleMoney = '';
var giftDescribeContent = '';
var giftDescribeTitle = '';
var disabled = true;
var gloData = app.globalData;
var codeString = '';
var Title1 = '';
var Title2 = '';
var Title3 = '';
var Content1 = '';
var Content2 = '';
var Content3 = '';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    sty: '0',
    // 点击之前
    score: 'rgba(131, 130, 130, 0.2)',
    score1: 'rgba(131, 130, 130, 0.2)',
    score2: 'rgba(131, 130, 130, 0.2)',
    scoreA: 'white',
    scoreB: 'white',
    scoreC: 'white',
    // 点击之后
    score3: 'rgba(131, 130, 130, 0.2)',
    score4: 'rgba(131, 130, 130, 0.2)',
    score5: 'rgba(131, 130, 130, 0.2)',
    scoreD: 'white',
    scoreE: 'white',
    scoreF: 'white',
    // currentData: 0,
    // 默认手机号
    BusinessEnterDefaultPhone: "",
    IsBusinessEnterIsDefaultPhone: "",
    phone: "",
    GiftDescribeContent: "",
    GiftDescribeTitle: "",
    getPhone: "",
    //立即购买 生成订单
    uid: "",
    setmealId: "",
    mobilePhone: "",
    entersignImg: "",
    app: "",
    // 生成订单信息
    orderData: "",
    // 生成订单号
    orderNumber: "",
    // 余额，微信
    payType: "",
    payFlag: true,
    //是否展示密码输入层
    showPayPwdInput: false,
    //输入的密码
    payPasswords: "",
    //文本框焦点
    payFocus: true,
    // 不同礼包支付金额
    type: 0,
    currentData: ['0', '1', '2'],
    aliTotalMoney: "",
    // 取得礼包
    GiftMaName: "",
    GiftGiveMaEdu: "",
    GiftGiveMaEduValidityDay: "",
    GiftConsumeMaEdu: "",
    GiftGiveMaEduValidityDay: "",
    GiftSaleMoney: "",
    top: [{
      'giftMaId': '白银',
      'active': true,
      'type': 0
    },
    {
      'giftMaId': '黄金',
      'active': false,
      'type': 1
    },
    {
      'giftMaId': '钻石',
      'active': false,
      'type': 2
    }
    ],
    json2: [],
    // giftMaName1:'白银',
    // giftMaName2:'黄金',
    // giftMaName3:'钻石'
    IsWeixinOpenId: ['0', '1'],
    focus: true,
    state: '',
    // 授权
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    powerFlag: true,
    phoneFlag: true,
    code: 'authMSG',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    this.setData({
      uid: wx.getStorageSync('uid'),
      userType: wx.getStorageSync('userType'),
      isAlreadyPayPassword: wx.getStorageSync('isAlreadyPasswords'),
    })
    // this.GetUserInfoByIDs();
    // this.topTap();
    this.GetUserInfoByIDs();

    // 登录
    var that = this;
    wx.login({
      success(res) {
        //js调用登陆命令获取到code
        if (res.code) {
          codeString = res.code
          //通过code调用自己服务接口获取到openid
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },
  // 授权登录
  bindAuthoriza: function () {
    var that = this;
    this.setData({
      powerFlag: false
    })
  },
  //获取授权用户的信息
  bindGetUserInfo(e) {
    wx.getSetting({
      success: res => {
        //如果经过授权
        if (res.authSetting['scope.userInfo']) {
          this.setData({
            hideBtn: true
          })
          //获取用户openid
          wx.getUserInfo({
            success: res => {
              var that = this;
              var uid = this.data.uid;
              var resultData = this.data.resultData;
              this.data.userInfo = res.userInfo,
                this.data.userInfo.code = gloData.code,
                wx.request({
                  url: baseJs.api + baseJs.encryUrl("method=GetSmallProgramOpenIdFromUserCode&Code=" + codeString + "&UID=" + this.data.uid),
                  success: function (res) {
                    // console.log(res);
                    resultData = JSON.parse(baseJs.decryUrl(res.data));
                    console.log(resultData);
                    // if (app.globalData.userInfo) {
                    that.setData({
                      userInfo: app.globalData.userInfo,
                      // uid: app.globalData.userInfo.uid,
                    })
                  }
                })
            }
          })
        }
      }
    })
  },
  // 授权登录
  powerTap: function () {
    this.setData({
      powerFlag: !this.data.powerFlag,
    })
    wx.showToast({
      title: '授权成功',
      icon: 'none',
      duration: 2000
    });
  },

  getUserInfo: function (e) {
    var that = this;
    var uid = this.data.uid;
    // console.log(e);
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      hasUserInfo: true,
    })
  },

  // 礼包
  bind1: function () {
    giftMaName = json1.ResultData[0].GiftMaName;
    giftMaId = json1.ResultData[0].GiftMaId;
    giftGiveMaEdu = json1.ResultData[0].GiftGiveMaEdu;
    giftGiveMaEduValidityDay = json1.ResultData[0].GiftGiveMaEduValidityDay;
    giftConsumeMaEdu = json1.ResultData[0].GiftConsumeMaEdu;
    giftSaleMoney = json1.ResultData[0].GiftSaleMoney;
    giftDescribeContent = json1.ResultData[0].GiftDescribeContent;
    giftDescribeTitle = json1.ResultData[0].GiftDescribeTitle;
    Title1 = giftDescribeTitle.split('|')[0];
    Title2 = giftDescribeTitle.split('|')[1];
    Title3 = giftDescribeTitle.split('|')[2];
    Content1 = giftDescribeContent.split('|')[0];
    Content2 = giftDescribeContent.split('|')[1];
    Content3 = giftDescribeContent.split('|')[2];
    this.setData({
      giftMaName: giftMaName,
      giftMaId: giftMaId,
      giftGiveMaEdu: giftGiveMaEdu,
      giftGiveMaEduValidityDay: giftGiveMaEduValidityDay,
      giftConsumeMaEdu: giftConsumeMaEdu,
      giftSaleMoney: giftSaleMoney,
      giftDescribeContent: giftDescribeContent,
      giftDescribeTitle: giftDescribeTitle,
      json1: json1,
      score: 'white',
      scoreA: 'black',
      sty: '0',
      score3: 'rgba(131, 130, 130, 0.2)',
      scoreD: 'white',
      Title1: Title1,
      Title2: Title2,
      Title3: Title3,
      Content1: Content1,
      Content2: Content2,
      Content3: Content3
    })

  },
  bind2: function () {
    giftMaName = json1.ResultData[1].GiftMaName;
    giftMaId = json1.ResultData[1].GiftMaId;
    giftGiveMaEdu = json1.ResultData[1].GiftGiveMaEdu;
    giftGiveMaEduValidityDay = json1.ResultData[1].GiftGiveMaEduValidityDay;
    giftConsumeMaEdu = json1.ResultData[1].GiftConsumeMaEdu;
    giftSaleMoney = json1.ResultData[1].GiftSaleMoney;
    giftDescribeContent = json1.ResultData[1].GiftDescribeContent;
    giftDescribeTitle = json1.ResultData[1].GiftDescribeTitle;
    Title1 = giftDescribeTitle.split('|')[0];
    Title2 = giftDescribeTitle.split('|')[1];
    Title3 = giftDescribeTitle.split('|')[2];
    Content1 = giftDescribeContent.split('|')[0];
    Content2 = giftDescribeContent.split('|')[1];
    Content3 = giftDescribeContent.split('|')[2];
    this.setData({
      giftMaName: giftMaName,
      giftMaId: giftMaId,
      giftGiveMaEdu: giftGiveMaEdu,
      giftGiveMaEduValidityDay: giftGiveMaEduValidityDay,
      giftConsumeMaEdu: giftConsumeMaEdu,
      giftSaleMoney: giftSaleMoney,
      giftDescribeContent: giftDescribeContent,
      giftDescribeTitle: giftDescribeTitle,
      json1: json1,
      score1: 'white',
      scoreB: 'black',
      sty: 1,
      score4: 'rgba(131, 130, 130, 0.2)',
      scoreE: 'white',
      Title1: Title1,
      Title2: Title2,
      Title3: Title3,
      Content1: Content1,
      Content2: Content2,
      Content3: Content3
    })
  },
  bind3: function () {
    giftMaName = json1.ResultData[2].GiftMaName;
    giftMaId = json1.ResultData[2].GiftMaId;
    giftGiveMaEdu = json1.ResultData[2].GiftGiveMaEdu;
    giftGiveMaEduValidityDay = json1.ResultData[2].GiftGiveMaEduValidityDay;
    giftConsumeMaEdu = json1.ResultData[2].GiftConsumeMaEdu;
    giftSaleMoney = json1.ResultData[2].GiftSaleMoney;
    giftDescribeContent = json1.ResultData[2].GiftDescribeContent;
    giftDescribeTitle = json1.ResultData[2].GiftDescribeTitle;
    Title1 = giftDescribeTitle.split('|')[0];
    Title2 = giftDescribeTitle.split('|')[1];
    Title3 = giftDescribeTitle.split('|')[2];
    Content1 = giftDescribeContent.split('|')[0];
    Content2 = giftDescribeContent.split('|')[1];
    Content3 = giftDescribeContent.split('|')[2];
    this.setData({
      giftMaName: giftMaName,
      giftMaId: giftMaId,
      giftGiveMaEdu: giftGiveMaEdu,
      giftGiveMaEduValidityDay: giftGiveMaEduValidityDay,
      giftConsumeMaEdu: giftConsumeMaEdu,
      giftSaleMoney: giftSaleMoney,
      giftDescribeContent: giftDescribeContent,
      giftDescribeTitle: giftDescribeTitle,
      json1: json1,
      score2: 'white',
      scoreC: 'black',
      sty: 2,
      score5: 'rgba(131, 130, 130, 0.2)',
      scoreF: 'white',
      Title1: Title1,
      Title2: Title2,
      Title3: Title3,
      Content1: Content1,
      Content2: Content2,
      Content3: Content3
    })
  },
  // //获取当前滑块的index
  // bindchange: function (e) {
  //   var that = this;
  //   var type = e.currentTarget.dataset.type;
  //   that.setData({
  //     type: e.detail.current
  //   })

  // },
  // //点击切换，滑块index赋值
  // checkCurrent: function (e) {
  //   var that = this;
  //   if (that.data.currentData == e.target.dataset.current) {
  //     return false;
  //   } else {
  //     that.setData({
  //       currentData: e.target.dataset.current
  //     })
  //     console.log(currentData);
  //   }
  // },

  // 点击不同礼包
  bindtype: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    that.setData({
      type: e.detail.current
    })
    console.log(type);
  },

  //获取查询输入的手机号
  phone: function (e) {
    var that = this;
    var phone = this.data.phone;
    console.log(e);
    this.setData({
      phone: e.detail.value
    })
    if (e.detail.value.length == 11) {
      that.getPhone();

    } else {
    }

  },
  //获取用户信息
  GetUserInfoByIDs: function () {
    var that = this;
    var uid = this.data.uid;
    var IsWeixinOpenId = this.data.IsWeixinOpenId;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetUserInfoByIDs&UID=" + uid),
      success: function (res) {
        console.log(JSON.parse(baseJs.decryUrl(res.data)));
        var json = JSON.parse(baseJs.decryUrl(res.data));
        that.setData({
          IsWeixinOpenId: json.ResultData.IsWeixinOpenId,
        })
      }
    })
  },
  // 获取礼包信息
  getPhone: function () {
    var that = this;
    var uid = this.data.uid;
    var phone = this.data.phone;
    var type = this.data.type;
    that.setData({
      giftMaId: giftMaId,
      type: type,
      giftGiveMaEdu: giftGiveMaEdu,
      giftGiveMaEduValidityDay: giftGiveMaEduValidityDay,
      giftConsumeMaEdu: giftConsumeMaEdu,
      giftSaleMoney: giftSaleMoney,
      giftMaName: giftMaName,
      giftDescribeContent: giftDescribeContent,
      giftDescribeTitle: giftDescribeTitle,
      json2: json2,
      giftMaName1: giftMaName1,
      giftMaName2: giftMaName2,
      giftMaName3: giftMaName3,
      disabled: false,
    })
    // 获取最下部礼包数据
    console.log("method=GetBuLuoMaRechargeSetMeal&UID=" + uid + "&MobilePhone=" + phone);
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetBuLuoMaRechargeSetMeal&UID=" + uid + "&MobilePhone=" + phone),
      success: function (res) {
        // console.log(res);
        var json = JSON.parse(baseJs.decryUrl(res.data));
        json1 = json;

        // for (var i = 0; i < json.ResultData.length; i++) {
        //   json2.push(json.ResultData[i].GiftMaName);
        // }
        // console.log(json2);
        if (json1.ResultData.length > 0) {
          giftMaName1 = json1.ResultData[0].GiftMaName;


        } if (json1.ResultData.length > 1) {
          giftMaName2 = json1.ResultData[1].GiftMaName;

        }
        if (json1.ResultData.length > 2) {
          giftMaName3 = json1.ResultData[2].GiftMaName;
        }
        // 取得礼包
        console.log(json);

        that.setData({
          giftMaId: giftMaId,
          type: type,
          giftGiveMaEdu: giftGiveMaEdu,
          giftGiveMaEduValidityDay: giftGiveMaEduValidityDay,
          giftConsumeMaEdu: giftConsumeMaEdu,
          giftSaleMoney: giftSaleMoney,
          giftMaName: giftMaName,
          giftDescribeContent: giftDescribeContent,
          giftDescribeTitle: giftDescribeTitle,
          json2: json2,
          giftMaName1: giftMaName1,
          giftMaName2: giftMaName2,
          giftMaName3: giftMaName3,
          focus: false,
        })

        that.bind1()

      }
    })
    // }
    // })
    // GiftMaId在生成订单时要带到立即购买里面
  },
  // 立即购买
  surePay: function () {
    var that = this;
    var uid = this.data.uid;
    var phone = this.data.phone;
    var IsWeixinOpenId = this.data.IsWeixinOpenId;
    if (IsWeixinOpenId == 1) {
      wx.request({
        url: baseJs.api + baseJs.encryUrl("method=GenerateBusinessEnterGiftOrder&UID=" + uid + "&SetMealId=" + giftMaId + "&MobilePhone=" + phone),
        success: function (res) {
          // console.log(res);
          var json = JSON.parse(baseJs.decryUrl(res.data));
          if (json.ResultFlag == 1) {
            wx.showToast({
              title: json.ResultMsg,
              icon: 'none',
              duration: 2000
            });
            // 生成订单
            console.log(json);
            var orderData = json.ResultData;
            that.setData({
              payFlag: false,
              orderData: orderData,
            })
            // 订单号
            // console.log(orderData);

          }
          else {
            wx.showToast({
              title: json.ResultMsg,
              icon: 'none',
              duration: 2000
            });
          }

        }
      })
    } else {
      wx.showToast({
        title: '请先授权！',
        icon: 'none',
        duration: 2000
      });
    }
  },
  //去支付
  goPay: function () {
    var that = this;
    var uid = this.data.uid;
    var payType = this.data.payType;
    var orderData = this.data.orderData;
    // var orderNumber = orderData.ordernumber;
    var aliTotalMoney = this.data.aliTotalMoney;
    var isAlreadyPayPassword = this.data.isAlreadyPayPassword;
    if (payType == '') {
      wx.showToast({
        title: "请选择支付方式！",
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    this.setData({
      payFlag: true,
    })
    if (payType == "1") {
      if (isAlreadyPayPassword == '1') {
        that.setData({
          showPayPwdInput: true,//弹出密码框
          payFocus: true
        })
      } else {
        wx.showToast({
          title: "请先去设置支付密码！",
          icon: 'none',
          duration: 1000
        });
      }
    } else {
      // 支付生成的礼包订单
      console.log("method=BusinessPayEnterGiftSmallProgramOrder&UID=" + uid + "&PayType=" + 2 + "&OrderNumber=" + orderData);
      wx.request({
        // 微信支付
        url: baseJs.api + baseJs.encryUrl("method=BusinessPayEnterGiftSmallProgramOrder&OrderNumber=" + orderData),
        success: function (res) {
          var json = JSON.parse(baseJs.decryUrl(res.data));
          console.log(json);
          if (json.ResultFlag == 1) {
            wx.requestPayment({
              timeStamp: json.ResultData.timeStamp,
              nonceStr: json.ResultData.nonceStr,
              package: json.ResultData.package,
              signType: json.ResultData.signType,
              paySign: json.ResultData.paySign,
              success(res) {
                console.log(res);
                wx.showToast({
                  title: '支付成功',
                  icon: 'none',
                  duration: 2000
                });
              },
              fail(res) {
                console.log(res);
                wx.showToast({
                  title: res.err_desc,
                  icon: 'none',
                  duration: 2000
                });
              }
            })
          } else {
            wx.showToast({
              title: json.ResultMsg,
              icon: 'none',
              duration: 2000
            });
          }
        }
      })
    }
  },
  // 支付弹出显示
  payShow: function () {
    this.setData({
      payFlag: !this.data.payFlag,
    })

  },
  //余额或微信 
  radioChange: function (e) {
    this.setData({
      payType: e.detail.value,
    });
  },
  //显示支付密码输入层
  showInputLayer: function () {
    this.setData({
      showPayPwdInput: true,
      payFocus: true,
    });
  },
  //隐藏支付密码输入层
  cancelInputPasswords: function () {
    var val = this.data.payPasswords;
    this.setData({
      showPayPwdInput: false,
      payFocus: false,
      payPasswords: '',
    });
  },
  // 获取焦点
  getFocus: function () {
    this.setData({
      payFocus: true
    });
  },
  //输入密码,监听
  inputPwd: function (e) {
    this.setData({
      payPasswords: e.detail.value
    });
  },
  //输入密码--确定 （余额支付）
  surePasswords: function () {
    var that = this;
    var uid = this.data.uid;
    var payPasswords = this.data.payPasswords;
    var orderData = this.data.orderData;
    var orderNumber = orderData.ordernumber;
    wx.request({
      // 支付密码是否正确
      url: baseJs.api + baseJs.encryUrl("method=CheckMyTradePassword&UID=" + uid + "&TradePassword=" + payPasswords),
      success: function (res) {
        var json = JSON.parse(baseJs.decryUrl(res.data));
        console.log(json);
        if (json.ResultFlag == 1) {//支付密码正确
          wx.request({
            // 余额支付
            url: baseJs.api + baseJs.encryUrl("method=BusinessPayEnterGiftOrder&UID=" + uid + "&PayType=" + 0 + "&OrderNumber=" + orderData),
            success: function (res) {
              var json = JSON.parse(baseJs.decryUrl(res.data))
              console.log(json);
              if (json.ResultFlag == 1) {//余额支付成功
                wx.showToast({
                  title: json.ResultMsg,
                  icon: 'none',
                  duration: 2000
                });
                  //商户入驻成功，发送信息
                  // var tmplIds = ['oRho5nar3sRFg5eOI4g8JwR_hkWrMxkhEcTGgb8DT28']
                  // wx.requestSubscribeMessage({
                  //   tmplIds: tmplIds,
                  //   success(res) {
                  //     console.log(res);
                  //     dingyue.shenhePass()
                  //   },
                  //   fail: err => {
                  //     console.log(err);
                  //   }
                  // })
                setTimeout(function () {
                  wx.navigateBack({
                    delta: 1
                  })
                }, 1000)
              } else {//余额支付失败
                wx.showToast({
                  title: json.ResultMsg,
                  icon: 'none',
                  duration: 2000
                });
              }
            }
          })
        } else {//支付密码错误
          wx.showToast({
            title: json.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })
  },
})